package server

import (
	"encoding/json"
	"fmt"
	"net/http"
	"runtime"
)

// 服务运行状态统计
const (
	statusIdentify = "status"
)

type status struct{}

type StatusInfo struct {
	Sys          uint64 `json:"mem_sys"` // 服务现在使用内存信息
	Alloc        uint64 `json:"mem_alloc"`
	HeadAlloc    uint64 `json:"heap_alloc"`
	HeapIdle     uint64 `json:"heap_idle"`
	HeapInuse    uint64 `json:"heap_inuse"`
	PauseToTalNs uint64 `json:"pause_to_nal_ns"`
}

func (s *StatusInfo) String() string {
	var str = "\t"
	str += fmt.Sprintf("Sys: %0.2fMB \t", float64(s.Sys)/1024/1024)
	str += fmt.Sprintf("Alloc: %0.2fMB \t", float64(s.Alloc)/1024/1024)
	str += fmt.Sprintf("HeadAlloc: %0.2fMB \t", float64(s.HeadAlloc)/1024/1024)
	str += fmt.Sprintf("HeapIdle: %0.2fMB \t", float64(s.HeapIdle)/1024/1024)
	str += fmt.Sprintf("HeapInuse: %0.2fMB \t", float64(s.HeapInuse)/1024/1024)
	str += fmt.Sprintf("PauseToTalNs: %d \t", s.PauseToTalNs)
	return str
}

func (s *status) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	var stat runtime.MemStats
	runtime.ReadMemStats(&stat)
	info := &StatusInfo{
		Sys:          stat.Sys,
		Alloc:        stat.Alloc,
		HeadAlloc:    stat.HeapAlloc,
		HeapIdle:     stat.HeapIdle,
		HeapInuse:    stat.HeapInuse,
		PauseToTalNs: stat.PauseTotalNs,
	}
	buf, _ := json.Marshal(info)
	response.Write(buf)
}

func init() {
	AddService(statusIdentify, &status{})
}
